package com.xixudi.htmlto;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * @Description 供爬网页资源用的下载类
 * @Author YangZheng 328170112@qq.com
 * @Date 2019-02-19 9:04
 */
public abstract class DownNode {
    private static final Logger log = LoggerFactory.getLogger(DownNode.class);
    protected String url;
    protected File file;
    protected String name;
    protected String type;
    protected Connection conn;
    protected Document doc;
    DownNode(String url,String type,boolean cover) {
        name = url.substring(url.lastIndexOf("/")==-1?0:url.lastIndexOf("/")+1);
        if(name.lastIndexOf("?")!=-1) name = name.substring(0,name.lastIndexOf("?"));
        int dot = url.lastIndexOf(".");
        if(dot==-1) {
            if(type==null) type = "html";
            name+=".html";
        } else {
            String suffix = url.substring(dot ==-1?0: dot);
            if(type==null) type = suffix;
        }
        this.type = type;
        this.url = url;
        this.makeUrl();
        file = new File(makeNewFilePath());
        if(!file.exists()||cover) {
            if (!"html".equals(type)) {
                File parentFile = file.getParentFile();
                if (!parentFile.exists()) parentFile.mkdir();
            }
            conn = Jsoup.connect(this.url).ignoreContentType(true);
            log.info("url:{}",url);
        } else {
            log.info("{} exists",this);
        }
    }
    DownNode(String url) {
        this(url,null,false);
    }
    DownNode(String url,String type) {
        this(url,type,false);
    }

    /**
     * @desc 根据url片段,拼接出完整url
     * @author YangZheng 328170112@qq.com
     * @date 2019-02-19 9:37
     */
    protected abstract String makeUrl();
    /**
     * @desc 将资源保存到本地的路径
     * @author YangZheng 328170112@qq.com
     * @date 2019-02-19 9:38
     */
    protected abstract String makeNewFilePath();

    public Document getDoc() throws IOException {
        if(doc==null) doc = conn.get();
        return doc;
    }
    public void saveToLocal() throws IOException {
        if(conn==null) return;
        Connection.Response resultImageResponse = conn.execute();
        FileOutputStream out = (new FileOutputStream(file));
        out.write(resultImageResponse.bodyAsBytes());
        out.close();
    }
    /**
     * @desc 将修改后的资源保存到本地
     * @author YangZheng 328170112@qq.com
     * @date 2019-02-19 9:38
     */
    public void saveDocToLocal() throws IOException {
        FileOutputStream fos = new FileOutputStream(file, false);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "utf8");
        osw.write(getDoc().html());
        osw.close();
    }
    @Override
    public String toString(){
        return "url:"+url;
    }
}
